<?php

namespace App\Http\Controllers;

use App\Mail\ValidateCodeEmail;
use App\Models\Admin;
use App\Models\Commission;
use App\Models\Role;
use App\Models\User;
use App\Rules\EmailRule;
use App\Rules\PhoneRule;
use App\Rules\UserExists;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Session;

class AuthController extends Controller
{
    public function __construct()
    {

        $this->middleware('auth:sanctum')->except(['login', 'logon', 'wechatLogin', 'emailTest']);
    }
    /**
     * 登录
     *
     * @param Request $request
     * @return 
     */
    public function login(Request $request)
    {
        Validator::make($request->input(), [
            "loginfield" => ['required', new UserExists()],
            "password" => ['required'],
            // "captcha" => ['required'],
            // "key" => ['required'],
        ])->validate();
        // 如果验证失败，返回错误响应
        // $captcha = $request->input('captcha');
        // $key = $request->input('key');
        // if (!captcha_api_check($captcha, $key, 'math')) {
        //     return $this->error('验证码错误');
        // }
        $value = $request->loginfield;
        $admin = Admin::with('roles')->where('phone', $value)->orWhere('email', $value)->orWhere('username', $value)->first();
        if ($admin->status === '2') {
            return $this->error('账号异常请联系管理员');
        }
        if ($admin && Hash::check($request->password, $admin->password)) {
            $tokens = $admin->createToken('auth', ['*']);
            return $this->success('登录成功', [
                'accessToken' => $tokens->plainTextToken,
                // 'refreshToken' => $tokens->accessToken,
                'tokenType' => 'Bearer'
            ]);
        }
        throw ValidationException::withMessages(['password' => '密码输入错误']);
    }

    /**
     * 后台退出登录
     *
     * @return 
     */
    public function logout()
    {

        // 检查用户是否已经认证
        if (Auth::check()) {
            // 用户已经认证
            // 清除当前登录用户信息
            $admin = Auth::user();
            // Revoke all tokens...
            $admin->tokens()->delete(); // 删除这个用户的所有令牌
            // $admin->user()->currentAccessToken()->delete();  // 删除当前请求的令牌
            return $this->success('退出登录成功');
        } else {
            // 用户未认证
            return $this->error('当前未登录');
        }
    }


    /**
     * 注册
     *
     * @param Request $request
     * @return 
     */
    public function logon(Request $request, Admin $admin)
    {
        Validator::make($request->input(), [
            "username" => ['required', 'regex:/^[a-z0-9]+$/', Rule::unique('admins')],
            "email" => ['required', 'email'],
            'code' => ['required', new EmailRule($request->input('email'))],
            'phone' => ['required', new PhoneRule()],
            "password" => ['required'],
        ])->validate();
        // 开启事务
        DB::beginTransaction();

        try {
            // 填充用户信息保存
            $admin->fill($request->input());
            $admin->status = 1; // 注册用户默认是正常状态
            $admin->role_id = Role::where('code', 'ordinaryUser')->first()->id; // 注册用户默认是普通用户
            $admin->password = Hash::make($request->password);
            $admin->save();

            // 当前文件的目录
            $currentDirectory = __DIR__;
            // 获取目录分隔符
            $separator = DIRECTORY_SEPARATOR;
            for ($i = 0; $i < 3; $i++) {
                $currentDirectory = dirname($currentDirectory);
            }
            $file_name = $currentDirectory . $separator . 'config' . $separator . 'defaultconfig.php';
            $data = include  $file_name;
            Commission::create([
                'admin_id' => $admin->id,
                'commission_top_rate' => $data['commission_top_rate'],
                'commission_sup_rate' => $data['commission_sup_rate']
            ]);
            // 提交事务
            DB::commit();
            return $this->success('注册成功', $admin->toArray());
        } catch (\Exception $e) {
            // 发生异常时回滚事务
            DB::rollback();
            return $this->error('注册失败', $e);
        }
    }

    /**
     * 获取登录用户信息和权限接口
     *
     * @param Request $request
     * @return 
     */
    public function me(Request $request)
    {
        $admin = Auth::user();
        // $admin
        $role = Role::where('id', $admin->role_id)->first();
        $perm = $role->menus->where('type', 'BUTTON')->pluck('perm');

        $data = [
            'roles' => [$admin->roles->code],
            'perms' => $perm,
            'userinfo' => $admin
        ];
        return $this->success('请求成功', $data);
    }

    /**
     * 获取路由接口
     *
     * @param Request $request
     * @return 
     */
    public function routes(Request $request)
    {
        // 处理路由
        function dataTree($data, $pid)
        {
            $branch = [];
            foreach ($data as $item) {
                if ($item->menus_id == $pid) {
                    $children = dataTree($data, $item->id);
                    $item->meta = [
                        'title' => $item->title,
                        'icon' => $item->icon,
                        'hidden' => $item->hidden ? true : false,
                        'roles' => $item->roles()->pluck('code')
                    ];
                    if ($children) {
                        $item->children = $children;
                    }
                    if ($item->type !== 'BUTTON') {
                        $branch[] =   $item;
                    }
                }
            }
            return $branch;
        }

        $role_id = Auth::user()->role_id;
        $role = Role::where('id', $role_id)->first();
        $route = $role->menus()->orderBy('order', 'ASC')->get();
        $data = dataTree($route, null);
        return $this->success('请求成功',  $data);
    }

    public function wechatLogin(Request $request, User $user)
    {

        // Validator::make($request->input(), [
        //     'code' => ['required'],
        //     'avatar' => ['required'],
        //     'nikename' => ['required']
        // ])->validate();
        // $code = $request->input('code');
        // $appid = env('WECHAT_APPID', 'wx9aff8a1abed6f878');
        // $secret = env('WECHAT_APPSECRET', '595e29e71596bafd419f86fcb6a3371e');
        // $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid . '&secret=' . $secret . '&js_code=' . $code . '&grant_type=authorization_code';

        // $response = $this->request_get($url);
        // if (!$response->successful()) {
        //     // 微信 API 请求失败，处理错误  
        //     return $this->error($response->message);
        // }

        // // 假设 $response->openid 是从微信 API 响应中提取的 openid  
        // $openid = $response->openid; // 根据你的实际响应结构提取 openid  

        // // 查找用户  
        $user = User::where('wechat', 'fffff')->first();

        if ($user) {
            $user->login_time = now();
            $user->save();
            $tokens = $user->createToken('auth', ['*']);
            $data = [
                'accessToken' => $tokens->plainTextToken,
                'tokenType' => 'Bearer',
                'userinfo' => $user
            ];
            // 用户已存在，返回用户信息  
            return $this->success('登录成功', $data);
        } else {
            // 用户不存在，注册新用户  
            $newUser = User::create([
                'wechat' => 'fffff',
                'avatar' => $request->input('avatar'),
                'username' => Str::uuid(),
                'nikename' => $request->input('nikename'),
                'login_time' => now(),
                'password' => Hash::make('123456'),
                // 其他用户信息，如用户名、邮箱等，根据需求添加  
            ]);
            $tokens = $newUser->createToken('auth', ['*']);
            $data = [
                'accessToken' => $tokens->plainTextToken,
                'tokenType' => 'Bearer',
                'userinfo' => $newUser
            ];
            // 返回新注册的用户信息  
            return $this->success('登录成功', $data);
        }
    }

    public function emailcode(Request $request)
    {
        Validator::make(['email' => $request->input('email')], [
            'email' => ['required', 'email']
        ])->validate();

        $view = 'emails.validate';    //发送邮箱的模版文件
        // $data = compact('user');    //发送到模版的数据
        $to = $request->input('email') || '2903404375@qq.com';         //邮箱接收地址
        $subject = '感谢您的注册！请确认你的邮箱。';
        $code = $this->generateVerificationCode();
        $email_content = [
            'title' => $subject,
            'name' => '天天开箱',
            'user' => '',
            'code' =>  $code,
            'body' => '',
            'view' => $view
        ];

        // Mail::to($to)->send(new ValidateCodeEmail($email_content));
        Session::put($to,  $code); // 有效期十分钟
        // $storedCode = Session::get($to);
        // $email_content['storedCode'] = $storedCode;
        return  $email_content;
    }
}
